package com.jxwifi.cloud.quickclean.upgrade;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.widget.RemoteViews;

import com.jxwifi.cloud.quickclean.MainActivity;
import com.jxwifi.cloud.quickclean.R;
import com.jxwifi.cloud.quickclean.bean.FileInfo;

import org.apache.http.HttpStatus;
import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DecimalFormat;

/**
 * Created by Administrator on 2019/5/24.
 */

public class UpdateService extends Service {


    private static String down_url; // = "http://192.168.1.112:8080/360.apk";
    private static final int DOWN_OK = 1; // 下载完成
    public static final String FILE_NAME = "kjb.quickclean.apk";
    public static final String DOWNLOAD_PATH = Environment.getExternalStorageDirectory().getAbsolutePath()
            + "/download/";
    private String app_name = "default";
    private NotificationManager notificationManager;
    private Notification.Builder notification;
    public final static String ACTION_BUTTON = "com.notifications.intent.action.ButtonClick";

    private Intent updateIntent;
    private PendingIntent pendingIntent;
    NetWorkStateReceiver netWorkStateReceiver;

    private int notification_id = 0;
    private FileInfo info;
    private DownLoadUtil downLoadUtil = null;
    RemoteViews contentView;
    private Notification.Builder mSannotification;
    /***
     * 更新UI
     */
    final Handler handler = new Handler() {
        @SuppressWarnings("deprecation")
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    FileInfo info = (FileInfo) msg.obj;
                    Log.w("oushuhua", "Handler" + info.toString());
                    //启动一个下载任务
                    downLoadUtil = new DownLoadUtil(UpdateService.this, info);
                    downLoadUtil.download();
                    break;
                case DOWN_OK:
                    // 下载完成，点击安装
                    notification.build().flags |= Notification.FLAG_AUTO_CANCEL;
                    notificationManager.cancel(notification_id);
                    update(new File(DOWNLOAD_PATH, FILE_NAME), UpdateService.this);//new File(updateFile)
                    stopService(updateIntent);
                    break;
                default:
                    stopService(updateIntent);
                    break;
            }
        }
    };

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        IntentFilter filter_click = new IntentFilter();
        filter_click.addAction(ACTION_BUTTON);
        registerReceiver(receiver_onclick, filter_click);//注册广播
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent != null) {
            try {
                app_name = intent.getStringExtra("app_name");
                down_url = intent.getStringExtra("downurl");
                info = new FileInfo(down_url, 0, 0, 0);
                if (netWorkStateReceiver == null) {
                    netWorkStateReceiver = new NetWorkStateReceiver();
                }
                IntentFilter filter = new IntentFilter();
                filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
                registerReceiver(netWorkStateReceiver, filter);

                EventBus.getDefault().register(this);
                // 创建通知
                createNotification();
                // 开始下载
                new MyThread(info).start();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return super.onStartCommand(intent, flags, startId);
    }

    @SuppressWarnings("deprecation")
    public void createNotification() {
            if (notificationManager == null)
                notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            if (notification == null)
                notification = new Notification.Builder(this);
            notification.setContentTitle(app_name)
                    .setSmallIcon(R.mipmap.ic_launcher);
           mSannotification = new Notification.Builder(this);
        NotificationChannel b;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            b = new NotificationChannel("1","默认通知", NotificationManager. IMPORTANCE_MIN);
            notificationManager.createNotificationChannel(b);
            mSannotification.setChannelId("1");
        }
            // 这个参数是通知提示闪出来的值
            mSannotification.setContentText("开始下载")
                    .setTicker("快洁帮正在下载...")
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setDefaults(Notification.DEFAULT_SOUND)
                    .build();
            updateIntent = new Intent(this, MainActivity.class);
            updateIntent.putExtra("mainindex", "0");
            updateIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
            pendingIntent = PendingIntent.getActivity(UpdateService.this,
                    0, updateIntent, PendingIntent.FLAG_CANCEL_CURRENT);
            mSannotification.setContentIntent(pendingIntent);

            //自定义通知
            contentView = new RemoteViews(getPackageName(), R.layout.notification_item);
            contentView.setTextViewText(R.id.notificationTitle, app_name);
            contentView.setTextViewText(R.id.notificationPercent, "0%");
            contentView.setProgressBar(R.id.notificationProgress, 100, 0, false);
            contentView.setImageViewResource(R.id.notificationImage, R.mipmap.ic_launcher);
            contentView.setImageViewResource(R.id.img_rel_notification, R.drawable.delete_img);

            //notification.setContent(contentView).build();

            //Intent Intent_pre = new Intent(ACTION_BUTTON);
            //PendingIntent pendIntent_click = PendingIntent.getBroadcast(this, 0, Intent_pre, 0);
            //notification.build().contentView.setOnClickPendingIntent(R.id.img_rel_notification, pendIntent_click);

            notificationManager.notify(notification_id, mSannotification.setContent(contentView).build());


    }

    private int mFrist = 1;

    @Subscriber(tag = "e-NetWorkState")
    private void getNetWorkState(boolean mBean) {
        if (mBean) {
            Log.w("test", "重新执行  MyThread");
            if (mFrist != 1) {
                if (downLoadUtil != null) {
                    downLoadUtil.isPause = true;
                }
                new MyThread(info).start();
            } else {
                mFrist = 2;
            }
        } else {
            if (downLoadUtil != null) {
                downLoadUtil.isPause = true;
            }
            Log.w("test", "downLoadUtil.isPause" + downLoadUtil.isPause);
        }
    }

    @Subscriber(tag = "e-Netfinished")
    private void getNetWorkState(int finished) {
        Log.w("oushuhua","finished=="+finished);
        DecimalFormat df1 = new DecimalFormat("0.00"); // ##.00%
        // 百分比格式，后面不足2位的用0补齐
        String result = df1.format(finished);
        contentView.setTextViewText(R.id.notificationPercent, result + "%");
        contentView.setProgressBar(R.id.notificationProgress, 100, finished, false);
        notificationManager.notify(notification_id, mSannotification.build());
    }

    @Subscriber(tag = "e-downOrver")
    private void getNetdownOrver(boolean finished) {
        Log.w("oushuhua","下载开始工作准备");
        Message message = handler.obtainMessage();
        message.what = DOWN_OK;
        handler.sendMessage(message);
    }

    /**
     * 安装程序
     * @param context
     */
    public static void update(File file, Context context) {
        Log.w("oushuhua"," 安装程序 update");
        Intent intent = new Intent(Intent.ACTION_VIEW);
        // 由于没有在Activity环境下启动Activity,设置下面的标签
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { //判读版本是否在7.0以上
            //参数1 上下文, 参数2 Provider主机地址 和配置文件中保持一致   参数3  共享的文件
            Uri apkUri = FileProvider.getUriForFile(context, "com.jxwifi.cloud.quickclean.provider", file);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        }
        context.startActivity(intent);
        CancelService(context);
    }

    private BroadcastReceiver receiver_onclick = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(ACTION_BUTTON)) {
                if (downLoadUtil != null) {
                    downLoadUtil.isPause = true;
                }
                notification.build().flags |= Notification.FLAG_AUTO_CANCEL;
                notificationManager.cancel(notification_id);
                if (downLoadUtil != null) {
                    downLoadUtil.delete(info);
                }
                CancelService(context);
            }
        }
    };

    public static void CancelService(Context context) {
        Intent intentStop = new Intent(context, UpdateService.class);
        context.stopService(intentStop);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterReceiver(netWorkStateReceiver);
        unregisterReceiver(receiver_onclick);
        EventBus.getDefault().unregister(this);
        Log.w("oushuhua", "com.jxwifi.cloud.quickclean.upgrade.UpdateService   onDestroy");
    }

    @Override
    public boolean onUnbind(Intent intent) {
        return super.onUnbind(intent);
    }

    @Override
    public void onRebind(Intent intent) {
        super.onRebind(intent);
    }

    //子线程  获取文件长度
    class MyThread extends Thread {
        private FileInfo fileInfo = null;

        public MyThread(FileInfo fileInfo) {
            this.fileInfo = fileInfo;
        }

        public void run() {

            Log.w("oushuhua","开始下载");
            HttpURLConnection urlConnection = null;
            RandomAccessFile randomFile = null;
            try {
                //连接网络
                URL url = new URL(fileInfo.getUrl());
                urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setConnectTimeout(3000);
                urlConnection.setRequestMethod("GET");
                int length = -1;
                if (urlConnection.getResponseCode() == HttpStatus.SC_OK) {
                    //获得文件长度
                    length = urlConnection.getContentLength();
                }
                if (length <= 0) {
                    return;
                }
                //本地文件
                File dir = new File(DOWNLOAD_PATH);
                Log.w("test", "Path" + DOWNLOAD_PATH);
                if (!dir.exists()) {
                    dir.mkdir();
                }
                File file = new File(dir, FILE_NAME);
                //可以在文件的任意位置进行操作
                randomFile = new RandomAccessFile(file, "rwd");
                //设置本地文件长度
                randomFile.setLength(length);
                //长度给fileInfo对象
                fileInfo.setLength(length);
                //传递给Service
                handler.obtainMessage(0, fileInfo).sendToTarget();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                urlConnection.disconnect();
                try {
                    if (randomFile != null) {
                        randomFile.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
